<template>
  <div class="install">
    <Vheader title="个人设置"></Vheader>
    <section class="main">
      <ul class="box">
        <li class="avatar"><label>头像</label>
          <div>
            <input type="file" name="uploadPicture" id="file" accept="image/*" ref="file" @change="send($event)">
            <div class="avatar-preview"><img :src="avatar" alt=""></div>
          </div>
          <span class="iconfont icon-right"></span>
        </li>
        <li @click="nick()"><span>昵称</span><span>{{username}}<span class="iconfont icon-right"></span></span></li>
        <li @click="setSex()"><span>性别</span><span>{{sextext}}<span class="iconfont icon-right"></span></span></li>
      </ul>
    </section>
    <section class="popup" v-show="sexShow">
      <div @click="hid()">

      </div>
      <ul>
        <li style="color: #313131;">请选择性别</li>
        <li @click="man('1')">男</li>
        <li @click="man('2')">女</li>
      </ul>
    </section>
  </div>
</template>

<script>
  import axios from '../../axios/axios'
  import {$} from '../../common/config'
  import Vheader from '../../components/header'

  export default {
    name: 'photo',
    data() {
      return {
        username: '',
        idcart: '',
        sex: 1,
        sextext: '',
        sexShow: false,
        files: [],
        popupVisible: '',
        avatar: '../../common/img/mescroll-empty.png'
      }
    },
    mounted: function () {
      this.inituserInfo();
    },
    methods: {
      inituserInfo: function () {
        var userinfo = JSON.parse(localStorage.getItem('user'));
        console.log(userinfo);
        this.avatar = userinfo.avatar;
        this.username = userinfo.nick;
        this.sex = userinfo.sex;
        if (this.sex === 1) {
          this.sextext = '男'
        } else if (this.sex === 2) {
          this.sextext = '女'
        } else if (this.sex === 3) {
          this.sextext = '未知'
        } else if (this.sex === 4) {
          this.sextext = '保密'
        }
      },
      nick: function () {
        this.$router.push('/nick');
      },
      setSex: function () {
        $('.popup').style.display = 'block';
      },
      hid: function (e) {
        $('.popup').style.display = 'none';
      },
      man: function (sex) {
        var that = this;
        var data = JSON.stringify({
          "data": [{
            sex: sex
          },
            13],
          "controllerName": "userInfo",
          "actionName": "update"
        });
        $('.popup').style.display = 'none';
        axios.postAdmain({
          data: data,
          callback(res) {
            console.log(res.data);
            var s = localStorage.getItem('user');
            s = JSON.parse(s);
            s.sex = parseInt(sex);
            localStorage.setItem('user', JSON.stringify(s));
            that.inituserInfo();

            console.log(res.data);
          }
        });
        this.sex = sex;
      },
      send: function (e) {
        var that = this;
        //    用于压缩图片的canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        //    瓦片canvas
        var tCanvas = document.createElement("canvas");
        var tctx = tCanvas.getContext("2d");
        var maxsize = 100 * 1024;
        var files = Array.prototype.slice.call(e.target.files);
        console.log(files)
        if (files.length > 1) {
          alert("最多同时只可上传1张图片");
          return;
        }
        files.forEach(function (file, i) {
          if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
          var reader = new FileReader();
          //          获取图片大小
          var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
          // li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
          // $(".img-list").append($(li));
          reader.onload = function () {
            var result = this.result;
            var img = new Image();
            img.src = result;
//            $(li).css("background-image", "url(" + result + ")");
            //如果图片大小小于100kb，则直接上传
            if (result.length <= maxsize) {
              img = null;
              upload(result, file.type, that);
              return;
            }
            //      图片加载完毕之后进行压缩，然后上传
            if (img.complete) {
              callback();
            } else {
              img.onload = callback;
            }

            function callback() {
              var data = compress(img);
              upload(data, file.type, that);
              img = null;
            }
          };
          reader.readAsDataURL(file);
        });

        //    使用canvas对大图片进行压缩
        function compress(img) {
          var initSize = img.src.length;
          var width = img.width;
          var height = img.height;
          //如果图片大于2百万像素，计算压缩比并将大小压至200万以下
          var ratio;
          if ((ratio = width * height / 2000000) > 1) {
            ratio = 0.7;
            console.log(ratio)
            // ratio =Math.pow(ratio,-4)
            width /= ratio;
            height /= ratio;
          } else {
            ratio = 1;
          }
          canvas.width = width;
          canvas.height = height;
          //        铺底色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, canvas.width, canvas.height);
          //如果图片像素大于100万则使用瓦片绘制
          var count;
          if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
            //            计算每块瓦片的宽和高
            var nw = ~~(width / count);
            var nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (var i = 0; i < count; i++) {
              for (var j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
              }
            }
          } else {
            ctx.drawImage(img, 0, 0, width, height);
          }
          //进行最小压缩
          var ndata = canvas.toDataURL('image/jpeg', 0.1);
          console.log('压缩前：' + initSize);
          console.log('压缩后：' + ndata.length);
          console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
          tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
          return ndata;
        }

        //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
        function upload(basestr, type, s) {
          console.log(type, s);
          var text = window.atob(basestr.split(",")[1]);
          var buffer = new Uint8Array(text.length);
          var pecent = 0, loop = null;
          for (var i = 0; i < text.length; i++) {
            buffer[i] = text.charCodeAt(i);
          }
          var blob = getBlob([buffer], type);
          var xhr = new XMLHttpRequest();
          var formdata = getFormData();
          var hw = parseInt(Math.sqrt(blob.size));
          formdata.append('files', blob);
          xhr.open('POST', 'http://139.224.132.124/upload?h=400&w=500&type=2');
          xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
              var jsonData = JSON.parse(xhr.responseText);
              console.log(jsonData.data.path[0])
              var img = jsonData.data.path[0];
              var data = JSON.stringify({
                "data": [{
                  "avatar": img,
                },
                  13],
                "controllerName": "userInfo",
                "actionName": "update"
              });
              axios.postAdmain({
                data: data,
                callback(res) {
                  console.log(res.data);
                  var user = localStorage.getItem('user');
                  user = JSON.parse(user);
                  console.log(user.avatar)
                  user.avatar = img;
                  s.avatar = img;
                  console.log(user.avatar)
                  localStorage.setItem('user', JSON.stringify(user));
                  // that.$router.go(-1);
                }
              })
            }
          };
          xhr.send(formdata);
        }

        /**
         * 获取blob对象的兼容性写法
         * @param buffer
         * @param format
         * @returns {*}
         */
        function getBlob(buffer, format) {
          try {
            return new Blob(buffer, {type: format});
          } catch (e) {
            var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
            buffer.forEach(function (buf) {
              bb.append(buf);
            });
            return bb.getBlob(format);
          }
        }

        /**
         * 获取formdata
         */
        function getFormData() {
          var isNeedShim = ~navigator.userAgent.indexOf('Android')
            && ~navigator.vendor.indexOf('Google')
            && !~navigator.userAgent.indexOf('Chrome')
            && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
          return isNeedShim ? new FormDataShim() : new FormData()
        }

        /**
         * formdata 补丁, 给不支持formdata上传blob的android机打补丁
         * @constructor
         */
        function FormDataShim() {
          console.warn('using formdata shim');
          var o = this,
            parts = [],
            boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
            oldSend = XMLHttpRequest.prototype.send;
          this.append = function (name, value, filename) {
            parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
            if (value instanceof Blob) {
              parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
              parts.push(value);
            }
            else {
              parts.push('\r\n\r\n' + value);
            }
            parts.push('\r\n');
          };
          // Override XHR send()
          XMLHttpRequest.prototype.send = function (val) {
            var fr,
              data,
              oXHR = this;
            if (val === o) {
              // Append the final boundary string
              parts.push('--' + boundary + '--\r\n');
              // Create the blob
              data = getBlob(parts);
              // Set up and read the blob into an array to be sent
              fr = new FileReader();
              fr.onload = function () {
                oldSend.call(oXHR, fr.result);
              };
              fr.onerror = function (err) {
                throw err;
              };
              fr.readAsArrayBuffer(data);
              // Set the multipart content type and boudary
              this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
              XMLHttpRequest.prototype.send = oldSend;
            }
            else {
              oldSend.call(this, val);
            }
          };
        }
      },
      openPage: function (url) {
        this.$router.push(url);
      },
    },
    components: {Vheader}
  }
</script>
<style type="text/scss" lang="scss" scoped>
  @import "../../common/style/iconfont.css";
  @import "../../common/style/public";

  .install {
    width: 100%;
    height: 100%;
    .box {
      margin-top: 5px;
      padding: 0 3vw;
      background-color: #FFFFFF;
      li {
        display: flex;
        justify-content: space-between;
        height: 46px;
        line-height: 46px;
        border-bottom: 1px solid #f5f5f5;
      }
      li.avatar {
        div {
          flex: 8;
          /*text-align: right;*/
          position: relative;
          input {
            display: block;
            width: 35px;
            height: 35px !important;
            position: absolute;
            top: 5.5px;
            right: 0;
            z-index: 2;
            opacity: 0;
          }
          .avatar-preview {
            position: absolute;
            width: 35px;
            height: 35px;
            top: 5.5px;
            right: 0;
            img {
              width: 100%;
              height: 100%;
              border-radius: 100%;
            }
          }
        }
      }
    }

    .up {
      width: 80vw;
      margin-left: 10vw;
      margin-top: 30vw;
    }

    .popup {
      display: none;
      width: 100%;
      height: 100%;
      position: fixed;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.5);
      ul {
        width: 80vw;
        background-color: #fff;
        border-radius: 8px;
        position: fixed;
        bottom: 10px;
        left: 10vw;
        z-index: 10;
        li {
          text-align: center;
          height: 36px;
          line-height: 36px;
          color: gray;
        }
        li:not(:nth-child(3)) {
          border-bottom: 1px solid #e3e3e3;
        }
      }
      div {
        width: 100%;
        height: 100%;
        position: fixed;
        bottom: 120px;
        left: 0;
        background-color: rgba(0, 0, 0, 0);
      }
    }
  }

</style>
